package cn.zch.soft.util.img2hex;
/***
 * @class ZxingQrUtils
 * @description TODO
 * @author zch
 * @date 2019/7/25
 * @version V0.0.1.201907251016.01
 * @functionpublic class ZxingQrUtils {}
 * @modfiyDate
 * @createDate
 * @package
 */
import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;

import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.CharacterSetECI;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import cn.zch.soft.util.qrcode.utils.qartutil.MatrixToImageConfig;
import cn.zch.soft.util.qrcode.utils.qartutil.MatrixToImageWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
 * QRCode生成工具类
 */
public class ImgQrZxingUtil {
	/**
	 * 二维码BufferedImage对象生成方法
	 * @param contents 二维码内容
	 * @param width 二维码图片宽度
	 * @param height 二维码图片高度
	 * @param margin 二维码边框(0,2,4,8)
	 * @author LinWenLi
	 * @date 2018-08-23 12:51:00
	 */
	public static BufferedImage createQrCode(String contents, int width, int height, int margin, Object level) {
		try {
			if (contents == null || "".equals(contents)) {
				throw new Exception("contents不能为空。");
			}
			// 二维码基本参数设置
			Map<EncodeHintType, Object> hints = new HashMap<>();
			// 设置编码字符集utf-8
			hints.put(EncodeHintType.CHARACTER_SET, CharacterSetECI.UTF8);
			// 设置纠错等级L/M/Q/H,纠错等级越高越不易识别，当前设置等级为最高等级H
			// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
			hints.put(EncodeHintType.ERROR_CORRECTION, level);
			// 可设置范围为0-10，但仅四个变化0 1(2) 3(4 5 6) 7(8 9 10)
			hints.put(EncodeHintType.MARGIN, margin);
			// 生成图片类型为QRCode
			BarcodeFormat format = BarcodeFormat.QR_CODE;
			// 创建位矩阵对象
			BitMatrix matrix = null;
			// 生成二维码对应的位矩阵对象
			matrix = new MultiFormatWriter().encode(contents, format, width, height, hints);
			// 设置位矩阵转图片的参数
			MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
			// 位矩阵对象转BufferedImage对象
			BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(matrix, config);
			System.out.println(qrCode.toString());
			return qrCode;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 二维码添加LOGO
	 * @param qrCode qrCode
	 * @param width 二维码图片宽度
	 * @param height 二维码图片高度
	 * @param logoPath 图标LOGO路径
	 * @param logoSizeMultiple 二维码与LOGO的大小比例
	 * @exception Exception Exception
	 * @author LinWenLi
	 * @date 2018-08-23 13:17:07
	 */
	public static BufferedImage createQRCodeWithLogo(BufferedImage qrCode, int width, int height, String logoPath, int logoSizeMultiple) throws Exception {
		File logoFile = new File(logoPath);
		if (!logoFile.exists() && !logoFile.isFile()) {
			throw new Exception("指定的LOGO图片路径不存在！");
		}
		try {
			// 读取LOGO
			BufferedImage logo = ImageIO.read(logoFile);
			// 设置LOGO宽高
			int logoHeight = qrCode.getHeight() / logoSizeMultiple;
			int logoWidth = qrCode.getWidth() / logoSizeMultiple;
			// 设置放置LOGO的二维码图片起始位置
			int x = (qrCode.getWidth() - logoWidth) / 2;
			int y = (qrCode.getHeight() - logoHeight) / 2;
			// 新建空画板
			BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			// 新建画笔
			Graphics2D g = (Graphics2D) combined.getGraphics();
			// 将二维码绘制到画板
			g.drawImage(qrCode, 0, 0, null);
			// 设置不透明度，完全不透明1f,可设置范围0.0f-1.0f
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
			// 绘制LOGO
			g.drawImage(logo, x, y, logoWidth, logoHeight, null);
			return combined;
		}
		catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	/**
	 * 导出到指定路径
	 * @param bufferedImage bufferedImage
	 * @param filePath 图片保存路径
	 * @param fileName 图片文件名
	 * @param formatName 图片格式
	 * @author LinWenLi
	 * @date 2018-08-23 12:59:03
	 */
	public static boolean generateQrCodeToPath(BufferedImage bufferedImage, String filePath, String fileName, String formatName) {
		// 判断路径是否存在，不存在则创建
		File path = new File(filePath);
		boolean canContinue = false;
		if (!path.exists()) {
			boolean mkDirOk = path.mkdirs();
			if (mkDirOk) {
				canContinue = true;
			}
		}
		else {
			canContinue = true;
		}
		boolean result = false;
		if (canContinue) {
			// 路径后补充斜杠
			if (filePath.lastIndexOf("\\") != filePath.length() - 1) {
				filePath = filePath + "\\";
			}
			// 组合为图片生成的全路径
			String fileFullPath = filePath + fileName + "." + formatName;
			try {
				// 输出图片文件到指定位置
				result = ImageIO.write(bufferedImage, formatName, new File(fileFullPath));
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	public static Result readQr(String qrFile) {
		try {
			MultiFormatReader formatReader = new MultiFormatReader();
			File file = new File(qrFile);
			BufferedImage image = ImageIO.read(file);
			BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
			//定义二维码参数
			HashMap hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			Result result = formatReader.decode(binaryBitmap, hints);
			System.out.println("解析结果" + result.toString());
			System.out.println("二维码类型" + result.getBarcodeFormat());
			System.out.println("二维码内容" + result.getText());
			return result;
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void main(String[] args) {
		//		// BufferedImage bufferedImage = createQrCode("16653", 320, 320, 0);
		//		String contents = "http://1.singbon.com/qrdt.do?dsn=99391089c29680c899391089c29680c899391089c29680c854b5947c87005e8991f2e222f1af8a27";
		//		// 二维码宽度
		//		int width = 64;
		//		// 二维码高度
		//		// int height = 320;
		//		// 二维码边距
		//		int margin = 0;
		//		// LOGO图片路径
		//		// String logoPath = "C:\\Users\\myComputer\\Desktop\\LOGO.jpg"
		//		// 二维码与LOGO的大小比例
		//		// int logoSizeMultiple = 3
		//		// 指定生成图片文件的保存路径
		//		String filePath = "E:\\T\\qr\\";
		//		// 生成的图片文件名
		//		String fileName = "_" + width;
		//		// 生成的图片格式，可自定义
		//		String formatName = "bmp";
		//		try {
		//			// 生成二维码
		//			BufferedImage qrCode = createQrCode(contents, width, width, margin,ErrorCorrectionLevel.H);
		//			// 添加LOGO
		//			// qrCode = createQRCodeWithLogo(qrCode, width, height, logoPath, logoSizeMultiple)
		//			// 导出到指定路径
		//			String fileFullPath = filePath + fileName + "." + formatName;
		//			System.out.println(fileFullPath);
		//			boolean result = generateQrCodeToPath(qrCode, filePath, fileName, formatName);
		//			System.out.println("执行结果" + result);
		//			readQr("D:\\PeopleFiles\\Azch\\Pic\\二维码\\成图发给客户\\王亮下载到设备\\16003-16018\\设备16003.bmp");
		//		}
		//		catch (Exception e) {
		//			e.printStackTrace();
		//		}
		try {
			int width = 64;
			int height = 64;
			// String contents = "http://yishuisheng.4000063966.com/qrdt.do?dsn=999999ABQWERTYUIOPASDFGHJKLMN";
			String contents = "http://yishuisheng.4000063966.com/qrdt.do?dsn=456789";
			System.out.println(contents.length());
			BufferedImage bufferedImage2 = ImgQrZxingUtil.createQrCode(contents, width, height, 0, ErrorCorrectionLevel.L);
			File outputfile = new File("E:/zchhhh/" + System.currentTimeMillis() + "_L.png");
			ImageIO.write(bufferedImage2, "png", outputfile);
			Thread.sleep(2000);
			bufferedImage2 = ImgQrZxingUtil.createQrCode(contents, width, height, 0, ErrorCorrectionLevel.M);
			File outputfile2 = new File("E:/zchhhh/" + System.currentTimeMillis() + "_M.png");
			ImageIO.write(bufferedImage2, "png", outputfile2);
			Thread.sleep(2000);
			bufferedImage2 = ImgQrZxingUtil.createQrCode(contents, width, height, 0, ErrorCorrectionLevel.Q);
			File outputfile3 = new File("E:/zchhhh/" + System.currentTimeMillis() + "_Q.png");
			ImageIO.write(bufferedImage2, "png", outputfile3);
			Thread.sleep(2000);
			bufferedImage2 = ImgQrZxingUtil.createQrCode(contents, width, height, 0, ErrorCorrectionLevel.H);
			File outputfile4 = new File("E:/zchhhh/" + System.currentTimeMillis() + "_H.png");
			ImageIO.write(bufferedImage2, "png", outputfile4);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
